package com.yuyou.activity.group.api.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.hibernate.validator.constraints.NotBlank;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.yuyou.activity.comm.service.tool.MailUtil;
import com.yuyou.activity.group.service.ActivityGroupSPConfig;
import com.yuyou.activity.group.service.entity.ActivityGroupbuy;
import com.yuyou.activity.group.service.entity.ActivityGroupbuyOrder;
import com.yuyou.activity.group.service.service.IActivityGroupSPService;
import com.yuyou.activity.group.service.service.IActivityGroupbuyOrderDetailService;
import com.yuyou.activity.group.service.service.IActivityGroupbuyOrderService;
import com.yuyou.activity.group.service.service.IActivityGroupbuyService;
import com.yuyou.activity.group.service.vo.resp.RespActivityGroupBuyOrderListVo;
import com.yuyou.activity.util.bean.PageParams;
import com.yuyou.activity.util.bean.Pagination;
import com.yuyou.activity.util.bean.ResBoolSimpleInfo;
import com.yuyou.activity.util.bean.ReturnResult;
import com.yuyou.activity.util.enums.ActivityGroupBuyEnums;
import com.yuyou.activity.util.enums.ActivityGroupBuyOrderEnums;
import com.yuyou.activity.util.util.LogUtil;
import com.yuyou.activity.util.util.Webs;


@Api(value="ActivityGroupSPController",description="ActivityGroupSP后台接口")
@Validated
@RestController
@RequestMapping(value="/api/admin/activityGroupSP")
public class ActivityGroupSPAdController extends BaseController{

    @Autowired
    private IActivityGroupbuyOrderService activityGroupbuyOrderService;

	@Autowired
	private IActivityGroupSPService activityGroupSPService;
	
    @Autowired
    private IActivityGroupbuyOrderDetailService activityGroupbuyOrderDetailService;
	
	@Autowired
	private IActivityGroupbuyService actGroupbuyService;
    
	@Autowired
	private MailUtil mailUtil;
    
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@ApiOperation(value="退款申请")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "projectCode", value = "项目编号", paramType = "query", required = true),
		@ApiImplicitParam(name = "orderId", value = "订单编号", paramType = "query", required = true)})
	@ResponseBody
	@RequestMapping(value="/refundByOrderId",method = {RequestMethod.GET, RequestMethod.POST})
	public ReturnResult<String> refundByOrderId(HttpServletRequest request,
			@NotBlank(message="项目编号不能为空") String projectCode,
			@NotBlank(message="订单编号不能为空") String orderId,String orderKey) throws Exception{
			if(ActivityGroupSPConfig.getConfig(projectCode).getRefundOpt().equals("1") && ActivityGroupSPConfig.getConfig(projectCode).getOrderKey().equals(orderKey)){	
				ResBoolSimpleInfo<String> res=activityGroupSPService.refundByOrderId(projectCode,orderId);	
				return ReturnResult.returnRes(res);
			}else if(ActivityGroupSPConfig.getConfig(projectCode).getRefundOpt().equals("0")){
				ResBoolSimpleInfo<String> res=activityGroupSPService.refundByOrderId(projectCode,orderId);	
				return ReturnResult.returnRes(res);
			}
			return ReturnResult.fail("没有权限");

	}
	
	@ApiOperation(value="部分退款申请")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "projectCode", value = "项目编号", paramType = "query", required = true),
		@ApiImplicitParam(name = "orderId", value = "订单编号", paramType = "query", required = true)})
	@ResponseBody
	@RequestMapping(value="/refundPartByOrderId",method = {RequestMethod.GET, RequestMethod.POST})
	public ReturnResult<String> refundPartByOrderId(HttpServletRequest request,
			@NotBlank(message="项目编号不能为空") String projectCode,
			@NotBlank(message="订单编号不能为空") String orderId,
			@NotNull(message="amount不能为空") Long amount,
			String orderKey) throws Exception{
			if(ActivityGroupSPConfig.getConfig(projectCode).getRefundOpt().equals("1") && ActivityGroupSPConfig.getConfig(projectCode).getOrderKey().equals(orderKey)){	
				ResBoolSimpleInfo<String> res=activityGroupSPService.refundPartByOrderId(projectCode,orderId,amount);
				return ReturnResult.returnRes(res);
			}else if(ActivityGroupSPConfig.getConfig(projectCode).getRefundOpt().equals("0")){
				ResBoolSimpleInfo<String> res=activityGroupSPService.refundPartByOrderId(projectCode,orderId,amount);
				return ReturnResult.returnRes(res);
			}
			return ReturnResult.fail("没有权限");

	}

	
	@ApiOperation(value="同步订单")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "projectCode", value = "项目编号", paramType = "query", required = true),
		@ApiImplicitParam(name = "orderId", value = "订单编号", paramType = "query", required = true)})
	@ResponseBody
	@RequestMapping(value="/sycnByOrderId",method = {RequestMethod.GET, RequestMethod.POST})
	public ReturnResult<String> sycnByOrderId(HttpServletRequest request,
			@NotBlank(message="项目编号不能为空") String projectCode,
			@NotBlank(message="订单编号不能为空") String orderId) throws Exception{
			ActivityGroupbuyOrder order=activityGroupbuyOrderService.selectByOrderId(projectCode, orderId);
			ResBoolSimpleInfo<String> res=activityGroupSPService.compensateOrder(order.getActivityGroupbuyOrderId());	
			return ReturnResult.returnRes(res);
	}
    
	
	@ApiOperation(value="同步sp")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "projectCode", value = "项目编号", paramType = "query", required = true),
		@ApiImplicitParam(name = "orderId", value = "订单编号", paramType = "query", required = true)})
	@ResponseBody
	@RequestMapping(value="/sycnSP",method = {RequestMethod.GET, RequestMethod.POST})
	public ReturnResult<String> sycnSP(HttpServletRequest request,
			@NotBlank(message="项目编号不能为空") String projectCode,
			@NotBlank(message="订单编号不能为空") String orderId) throws Exception{
      	ActivityGroupbuyOrder order=activityGroupbuyOrderService.selectByOrderId(projectCode, orderId);
        try { 
            if(order == null){               
                LogUtil.error(logger ,"");
    			return ReturnResult.fail("没有订单");
            }else if(order.getPayStatus().intValue()!=ActivityGroupBuyOrderEnums.payStatus.SUCCESS.getValue()){  
                LogUtil.error(logger ,"");
    			return ReturnResult.fail("不是支付状态");
            }else if(order.getIsSync()!=null && order.getIsSync().intValue()==2){  
                LogUtil.error(logger ,"");
    			return ReturnResult.fail("不能重复同步");
            }else {           	
//        		ActivityGroupbuy activityGroupbuy = actGroupbuyService.selectByPrimaryKey(order.getActivityGroupbuyId());       		
//        		if(activityGroupbuy.getStatus().intValue()!=ActivityGroupBuyEnums.status.TRUE_SUCCESS.getValue()
//        				|| activityGroupbuy.getStatus().intValue()!=ActivityGroupBuyEnums.status.FAKE_SUCCESS.getValue()){
//        			return ReturnResult.fail("不是满团状态");
//        		}
            	
                List<Long> resourceList =  activityGroupbuyOrderDetailService.findSourceIdByOrderId(order.getActivityGroupbuyOrderId());
                if(resourceList.size() > 0 ){
                    String ids = "";
                    for (Long i :
                            resourceList) {
                        ids = ids + i + ",";
                    }
                    //同步至shipin.com
                    ReturnResult<String> result = activityGroupSPService.synchUserOrder2Shipin(order.getName() , order.getPhone() , ids.substring(0 , ids.length() -1));
                    if(result.isSuccess()){
                        LogUtil.info(logger , "ad同步至shipin.com成功");
                        ActivityGroupbuyOrder updateOrder=new ActivityGroupbuyOrder();
                		updateOrder.setActivityGroupbuyOrderId(order.getActivityGroupbuyOrderId());
                		updateOrder.setIsSync(ActivityGroupBuyOrderEnums.isSync.SUCCESS.getValue());
                        activityGroupbuyOrderService.updateByPrimaryKeySelective(updateOrder);
                    }else {
                        LogUtil.warn(logger , "ad同步至shipin.com失败：" + result.getDesc());
                        ActivityGroupbuyOrder updateOrder=new ActivityGroupbuyOrder();
                		updateOrder.setActivityGroupbuyOrderId(order.getActivityGroupbuyOrderId());
                		updateOrder.setIsSync(ActivityGroupBuyOrderEnums.isSync.FAIL.getValue());
                        activityGroupbuyOrderService.updateByPrimaryKeySelective(updateOrder);
                    }

                }
            }
        } catch (Exception e) {
            LogUtil.error(logger , e.getMessage());
			return ReturnResult.fail( e.getMessage());
        }	
			return ReturnResult.success("ok");

	}
	
    
    @ApiOperation(value="获取所有用户订单数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "projectCode", value = "项目编号", paramType = "query"),
            @ApiImplicitParam(name = "text", value = "关键字", paramType = "query"),
            @ApiImplicitParam(name = "orderId", value = "订单编号", paramType = "query"),
            @ApiImplicitParam(name = "phone", value = "手机号", paramType = "query"),
            @ApiImplicitParam(name = "payStatus", value = "订单状态", paramType = "query")})
    @ResponseBody
    @RequestMapping(value="/getAllUserOrders",method = {RequestMethod.GET, RequestMethod.POST})
    public ReturnResult<RespActivityGroupBuyOrderListVo> getAllUserOrders(@Validated @ModelAttribute PageParams pageParams,
                                                                          String projectCode,String text,
                                                                          String orderId, Integer payStatus,String phone){
            Map<String, Object> conditions = new HashMap<>();
            Pagination<RespActivityGroupBuyOrderListVo> queryPgn = new Pagination<>();
            if(!StringUtils.isEmpty(projectCode)){
                conditions.put("projectCode", projectCode);
            }            
            if(!StringUtils.isEmpty(text)){
                conditions.put("text", text.trim());
            }
            if(!StringUtils.isEmpty(orderId)){
                conditions.put("orderId", orderId.trim());
            }
            if(!StringUtils.isEmpty(payStatus)){
                conditions.put("payStatus", payStatus);
            }
            if(!StringUtils.isEmpty(phone)){
                conditions.put("phone", phone);
            }            

            queryPgn.setConditions(conditions);
            queryPgn.setPageParams(pageParams);

            int total = activityGroupbuyOrderService.getAllUserOrderCount(queryPgn);
            queryPgn.setTotal(total);
            queryPgn.toBePage();
            if(total > 0){
                List<RespActivityGroupBuyOrderListVo> list = activityGroupbuyOrderService.getAllUserOrder(queryPgn);
                queryPgn.setList(list);
            }

            return ReturnResult.success(queryPgn);


    }

    @ApiOperation(value="导出订单数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "projectCode", value = "项目编号", paramType = "query", required = true),
            @ApiImplicitParam(name = "text", value = "关键字", paramType = "query"),
            @ApiImplicitParam(name = "orderId", value = "订单编号", paramType = "query"),
            @ApiImplicitParam(name = "phone", value = "手机号", paramType = "query"),
            @ApiImplicitParam(name = "payStatus", value = "订单状态", paramType = "query")})
    @RequestMapping(value="/exportOrders",method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<String> exportOrders(@NotBlank(message="项目编号不能为空") String projectCode,String text,String orderId, Integer payStatus,String phone,
                            HttpServletRequest request , HttpServletResponse response){
        HSSFWorkbook hssfWorkbook = activityGroupSPService.excelSPOrders(projectCode , text , orderId , payStatus , phone);
        Webs.writeHSSFExcel(request, response, hssfWorkbook , "反三科订单表");
        return ReturnResult.success("OK");
    }
	
	
}
